package com.zte.claa.inficombo.csa.app.service.gprscat1.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GPRSDevSvrHandler extends IoHandlerAdapter {

	private  Logger logger = LoggerFactory.getLogger(GPRSDevSvrHandler.class);
	private  GPRSDevServerManager conSvrManager;
	
	public GPRSDevSvrHandler(GPRSDevServerManager conSvrManager) {
         this.conSvrManager = conSvrManager;
	}
	
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("session opened: " + session.getId());
		this.conSvrManager.onSessionOpened(session);
		super.sessionOpened(session);		
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("session closed: " + session.getId()+", remoteAddr="+session.getRemoteAddress());
		this.conSvrManager.onSessionClosed(session);
		super.sessionClosed(session);		
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		logger.info("session idled: " + session.getId());
		this.conSvrManager.onSessionIdle(session, status);
		super.sessionIdle(session, status);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("exception: " + cause.getMessage()+", remoteAddr="+session.getRemoteAddress(), cause);
		this.conSvrManager.OnExceptionCaught(session, cause);
		super.exceptionCaught(session, cause);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.debug("session message received: " + session.getId()+ ", msg: " + message);
		this.conSvrManager.onMessageReceived(session, message);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.debug("session message sent: "+session.getId()+", msg: "+message.toString());
	}

	public void inputClosed(IoSession session) throws Exception {
		logger.info("session = "+session.getId()+": inputClosed! "+", remoteAddr="+session.getRemoteAddress());
		// 避免死循环触发inputClosed()方法。
		// session.close(true);
		session.closeNow();
		//this.conSvrManager.onSessionClosed(session);
		//super.inputClosed(session);
	}
}
